package tech.yangzhijie.basic.knowledge.mianshi;

import java.util.concurrent.*;

public class Test12ThreadPool {



    public static void main(String[] args) {
        //使用Executors创建线程池();
        //不使用Executors创建线程池();//使用抛异常策略
        //使用CallRunsPolicy();
        //使用丢弃策略();
        使用丢弃老的策略();
    }

    private static void 使用Executors创建线程池(){
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        处理十个窗口任务(executorService);
    }

    /**
     * 支持定时以及周期性执行任务的线程池
     */
    private static void scheduledThreadPoolExecutor(){
        ExecutorService executorService = Executors.newScheduledThreadPool(1);

    }

    private static void 不使用Executors创建线程池(){
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 3, 2, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());

        处理十个窗口任务(threadPoolExecutor);
    }

    private static void 使用CallRunsPolicy(){
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 3, 2, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());

        处理十个窗口任务(threadPoolExecutor);
    }

    private static void 使用丢弃策略(){
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 3, 2, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(), new ThreadPoolExecutor.DiscardPolicy());

        处理十个窗口任务(threadPoolExecutor);
    }

    private static void 使用丢弃老的策略(){
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 3, 2, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(), new ThreadPoolExecutor.DiscardOldestPolicy());

        处理十个窗口任务(threadPoolExecutor);
    }

    private static void 处理十个窗口任务(ExecutorService executorService){
        try {
            for (int i = 1; i <= 10; i++) {
                final int num = i;
                executorService.execute(()->{
                    System.out.println("窗口 " + Thread.currentThread().getName() + " 给第 " + num + " 号客户办理业务");
                });
            }
        }catch (RejectedExecutionException e) {
            e.printStackTrace();
        }finally {
            executorService.shutdown();
        }
    }
}
